package com.ckzp.jfinal.system.util;

import com.ckzp.core.Results;
import com.ckzp.core.util.StringUtil;
import com.ckzp.jfinal.plugins.cron4j.MyCron4jPlugin;
import com.ckzp.jfinal.system.model.SysTask;
import com.ckzp.jfinal.system.model.SysWorklog;
import com.ckzp.plugins.ip.IpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import it.sauronsoftware.cron4j.Task;

import java.util.Date;
import java.util.List;

/**
 * Created by 51594 on 2022/3/29.
 */
public class SysTaskUtil {

    public static SysTaskUtil n() {
        return new SysTaskUtil();
    }

    /**
     * @param task_id
     * @return
     */
    public Results startTask(int task_id) {
        String name = "task_" + task_id;
        boolean status = false;
        MyCron4jPlugin.removeTask(name);
        return addTask(task_id);
    }

    /**
     * @param task_id
     * @return
     */
    public Results stopTask(int task_id) {
        String name = "task_" + task_id;
        boolean status = MyCron4jPlugin.stopTask(name);
        return Results.n(status ? 0 : 9, "计划任务已停止");
    }

    /**
     * 添加任务
     *
     * @param task_id
     * @return
     */
    public Results addTask(int task_id) {
        Results results = Results.n().setMsg("加载成功");
        try {
            String name = "task_" + task_id;
            SysTask task = SysTask.dao.findById(task_id);
            if (task != null) {
                String cron = task.mod.getStr("task_cron");
                String task_class = task.mod.getStr("task_class");
                Object taskObj = Class.forName(task_class).newInstance();
                if (taskObj instanceof Runnable) {
                    MyCron4jPlugin.getPlugin().addTask(name, cron, (Runnable) taskObj, true, true, true);
                } else if (taskObj instanceof Task) {
                    MyCron4jPlugin.getPlugin().addTask(name, cron, (Task) taskObj, true, true, true);
                } else {
                    results.setCode(9).setMsg("class:" + task_class + " error");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            results.setCode(9).setMessage(e.getMessage());
        }
        return results;
    }

    /**
     * 从数据库中读取初始化计划任务
     */
    public void initAllTask() {
        List<SysTask> list = SysTask.dao.findAll();
        for (SysTask task : list) {
            if (task.mod.getInt("is_auto", 1) == 1) addTask(task.mod.getInt("task_id"));
        }
    }


    /**
     * 关闭所有计划任务
     */
    public void closeAllTask() {
        List<SysTask> list = SysTask.dao.findAll();
        for (SysTask task : list) {
            stopTask(task.mod.getInt("task_id"));
        }
    }

    /**
     * @param taskName
     */
    public void updateLastAction(String taskName) {
        try {
            final String taskid = StringUtil.replace(taskName, "task_", "");
            SysTask task = SysTask.dao.findById(taskid);
            if (task != null) {
                task.set("last_done", new Date()).update();
                if (task.getInt("is_log") == 1) {
                    SysWorklog worklog = new SysWorklog();
                    worklog.set("log_result", 1).set("log_title", "执行成功").set("log_time", new Date());
                    worklog.set("log_ip", "127.0.0.1").set("log_os", "").set("log_browser", "").set("log_desc", "");
                    worklog.set("key1", taskName);
                    worklog.set("log_type", 98).set("emp_id", 0).set("user_name", "").set("login_id", "");

                    SysWorkLogUtil.n().saveLog(worklog);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param taskName
     */
    public void updateLastAction(String taskName, String errMessage) {
        try {
            final String taskid = StringUtil.replace(taskName, "task_", "");
            SysTask task = SysTask.dao.findById(taskid);
            if (task != null) {
                task.set("last_done", new Date()).update();
                if (task.getInt("is_log") == 1) {
                    SysWorklog worklog = new SysWorklog();
                    worklog.set("log_result", 2).set("log_title", "执行失败").set("log_time", new Date());
                    worklog.set("log_ip", "127.0.0.1").set("log_os", "").set("log_browser", "").set("log_desc", errMessage);
                    worklog.set("key1", taskName);
                    worklog.set("log_type", 98).set("emp_id", 0).set("user_name", "").set("login_id", "");
                    SysWorkLogUtil.n().saveLog(worklog);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 现在就执行一次
     *
     * @param task_id
     */
    public Results runSysTask(int task_id) {
        return Results.n().setCode(MyCron4jPlugin.runTask("task_" + task_id) ? 0 : 9).setMsg("执行成功");
    }
}
